

import { STATE } from "./oribits/OrbitControls.ts";
import { UIStateEvent } from "../events";
import { Controller } from "./types";
import { Intersection, Object3D } from "three";

/**
 * 选取处理器
 */
export class PickupHandler extends Controller {
  #currentRays: Intersection<Object3D>[] = []
  picks: Set<Object3D> = new Set()
  get currentVisibleObjects() {
    return this.#currentRays.map(i => i.object).filter(o => o.visible) || []
  }
  constructor() {
    super();
  }
  handler = ({ detail, renderer }: UIStateEvent) => {


    if (detail.pointerDownButton !== STATE.NONE) {
      return
    }
    renderer.rayCaster.setFromCamera(detail.currentNormalizedXOY, renderer.camera);
    const intersects = renderer.rayCaster.intersectObjects(renderer.scene.children) || [];
    this.#currentRays = intersects || []
    const choosed = this.currentVisibleObjects.at(0)
    if (!choosed && !detail.ctrlKey) {
      this.picks.clear()
    }
    if (detail.ctrlKey && choosed) {
      this.picks.add(choosed)
    } else if (choosed) {
      this.picks.clear();
      this.picks.add(choosed)
    }
    if (this.picks.size === 0) {
      renderer.outline.selectedObjects = []
      
    }else{
      renderer.outline.selectedObjects = Array.from(this.picks.values())
    }
    
  }

}
